package com.mes.controller.manu;

import com.interf.WCSUtils;
import com.mes.entity.*;
import com.mes.service.manu.DataCollectionService;
import com.mes.service.manu.ProcessService;
import com.yy.base.common.action.BaseCtrl;
import com.yy.base.common.service.EntityService;
import com.yy.base.page.Message;
import com.yy.base.util.StringUtil;
import com.yy.base.util.UserUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("dataCollection")
public class DataCollectionController extends BaseCtrl {
	@Autowired
	private EntityService service;
	@Autowired
	private DataCollectionService dcService;
	@Autowired
	private ProcessService processService;
	public static final String[] KEYS = new String[]{"DATA1", "DATA2", "DATA3", "DATA4", "DATA5", "DATA6", "DATA7", "DATA8", "DATA9", "DATA10",
			"DATA11", "DATA12", "DATA13", "DATA14", "DATA15", "DATA16", "DATA17", "DATA18", "DATA19", "DATA20"};

	//获取生产工单信息
	@ResponseBody
	@RequestMapping(value = "searchOrderInfo", method = RequestMethod.POST)
	public Message searchOrderInfo(HttpServletRequest request) {
		Message msg = new Message();
		try {
			String orgId = (String) request.getSession().getAttribute("orgId");
			String code = request.getParameter("code").toUpperCase();
			String pageCode = request.getParameter("pageCode");
			User user = this.getLoginUser(request);

			DataCollectionPage page = dcService.getDataCollectionPage(pageCode);
			Map<String, Object> data = dcService.searchOrderInfo(code, page, user.getId(), orgId);

			if (data == null) {
				msg.setErrorMessage("根据编码未找到对应的工单！");
			} else {
				//跟不同的工序，通过扫码的工单号下料对应的楦头、夹板、压底模
				outMaterialToWms(page.getEmesProcessOprId(), code);

				dcService.getfishCollectionPage(code, pageCode, orgId);
				//获取工艺作业指导书
				String fileId = dcService.getSopFileId(code, page.getEmesProcessOprId());
				msg.setData("fileId", fileId);
				if (orgId != null && !orgId.equals(data.get("AD_ORG_ID"))) {
					msg.setErrorMessage("此工单为" + data.get("ORGNAME") + "所有，不能在本车间执行！");
				} else {
					msg.setData(data);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrorMessage("查询异常：" + e.getMessage());
		}
		return msg;
	}

	//获取设备信息
	@ResponseBody
	@RequestMapping(value = "getFacilitiesInfo", method = RequestMethod.POST)
	public Message getFacilitiesInfo(HttpServletRequest request) {
		Message msg = new Message();
		try {
			String code = request.getParameter("code");
			Map<String, Object> data = dcService.getFacilitiesInfo(code);
			if (data == null) {
				msg.setErrorMessage("根据编码未找到对应的设备信息！");
			} else {
				msg.setData(data);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrorMessage("查询异常：" + e.getMessage());
		}
		return msg;
	}

	//获取页面历史数据
	@ResponseBody
	@RequestMapping(value = "getHistoryList", method = RequestMethod.POST)
	public Message getHistoryList(HttpServletRequest request) {
		Message msg = new Message();
		try {
			String id = request.getParameter("id");
			String pageCode = request.getParameter("pageCode");
			DataCollectionPage page = dcService.getDataCollectionPage(pageCode);

			String orgId = (String) request.getSession().getAttribute("orgId");
			User user = this.getLoginUser(request);
			List<Map<String, Object>> data = dcService.getHistoryList(page, id, user.getId(), orgId);
			msg.setSplitPageList(data);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrorMessage("查询异常：" + e.getMessage());
		}
		return msg;
	}

	//获取生产采集页面信息
	@ResponseBody
	@RequestMapping(value = "getDataCollectionPage", method = RequestMethod.POST)
	public Message getDataCollectionPage(HttpServletRequest request) {
		Message msg = new Message();
		try {
			String code = request.getParameter("code");
			String orgId = (String) request.getSession().getAttribute("orgId");
			msg.setData("orgId", orgId);

			DataCollectionPage page = dcService.getDataCollectionPage(code);
			if (page == null) {
				msg.setErrorMessage("编码[" + code + "]未找到对应的生产采集页面信息！");
			} else {
				List<DataCollectionTab> list = dcService.getDataCollectionTab(page.getEmesDCInputPageId());
				//判定工序是否需要采集设备数据
				msg.setData("Dc_Btn_List", list);
				msg.setData("data", page);
			}
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrorMessage("查询异常：" + e.getMessage());
		}
		return msg;
	}

	//保存生产工序信息(开工时间、设备、操作人)
	@ResponseBody
	@RequestMapping(value = "saveJobOrderInfo", method = RequestMethod.POST)
	@Transactional
	public Message saveJobOrderInfo(HttpServletRequest request) {
		Message msg = new Message();
		int num = 0;
		String pageCode = request.getParameter("pageCode");
		String orderCode = request.getParameter("orderCode");
		String facCode = request.getParameter("facCode");
		String userCode = request.getParameter("userCode");
		String status = request.getParameter("status");

		String isRework = request.getParameter("isRework");
		String description = request.getParameter("description");
		String userId = (String) request.getSession().getAttribute("userId");
		String orgId = (String) request.getSession().getAttribute("orgId");

		//根据页面编码获取工序信息
		DataCollectionPage pageInfo = dcService.getDataCollectionPage(pageCode);
		if (pageInfo == null) {
			msg.setErrorMessage("编码[" + pageCode + "]未找到对应的生产采集页面信息！");
			return msg;
		}

		if (pageInfo.isScanUser()) {
			userId = dcService.geteUserId(userCode);
			if (userId == null) {
				msg.setErrorMessage("工号[" + userCode + "]录入错误！");
				return msg;
			}
		}
		Map<String, Object> mapEre = dcService.getDataCollectionPage(pageCode, orderCode, orgId);

/*		//验证上道工序是否已完工
		String error = dcService.checkBatchProcess(orderCode, pageInfo.getProcessId());
		if (error != null && !"".equals(error)) {
			msg.setErrorMessage(error);
			return msg;
		}*/
		EmesoJobOrder orderInfo = dcService.getJobOrder(orderCode);
		//获取工序配置信息
		Map<String, Object> process = processService.getProcessInfo((String) mapEre.get("EMES_PROCESS_ID"));

		EmesoJobOrderExe jobExe = dcService.getJobOrderExe(orderInfo.getId(), (String) mapEre.get("EMES_PROCESS_ID"));
//		if (jobExe != null) {
			status = dcService.updateJobOrder(orderCode, (String) process.get("ID"), (String) process.get("NAME"), userId, facCode, status);
//		} else {
//			dcService.saveJobOrder(orderCode, (String) process.get("ID"), (String) process.get("NAME"), orgId, userId, facCode, "START", isRework, description);
//		}
		if (status != null) {
			msg.setOkMessage(process.get("NAME") + "处理成功！");
		} else {
			msg.setData("status", status);
		}
		return msg;
	}

	//获取工序列表
	@ResponseBody
	@RequestMapping(value = "getProcessList", method = RequestMethod.POST)
	public Message getProcessList(HttpServletRequest request) {
		Message msg = new Message();
		try {
			Map<String, Object> params = new HashMap();

			String sql = "select Emes_Process_Id, route_no, ep.name, next_route_no, process_time from Emes_Process ep, Emes_Process_Route pr " +
					"where pr.is_default = 'Y' and ep.Emes_Process_Route_Id = pr.Emes_Process_Route_Id";

			String orderCode = request.getParameter("orderCode");
			if (StringUtil.isNotEmpty(orderCode)) {
				sql += "  and exists (select 1 from emeso_Manuorder mo where mo.Emes_Process_Route_Id = pr.Emes_Process_Route_Id and mo.code = :orderCode)";
				params.put("orderCode", orderCode);
			}

			List<Map<String, Object>> list = service.query(sql + " order by ep.route_no", params);
			msg.setData("data", list);
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrorMessage("查询异常：" + e.getMessage());
		}
		return msg;
	}

	//保存数据采集的数据
	@ResponseBody
	@PostMapping("saveDCData")
	public Message saveDCData(HttpServletRequest request) {
		Message msg = new Message();
		String pageId = request.getParameter("pageId");
		if (pageId != null && pageId != "") {
			String sql = "select table_name from Emes_DC_Input_Data where Emes_DC_Input_Data_id = ?";
			Map<String, Object> tableMap = service.queryUnique(sql, pageId);
			if (tableMap != null) {
				String tableName = String.valueOf(tableMap.get("TABLE_NAME"));
				String data = request.getParameter("data");
				JSONArray dataArray = JSONArray.fromObject(data);
				List<Object> params = new ArrayList<Object>();
				for (int i = 0; i < dataArray.size(); i++) {
					sql = "update " + tableName + " set AD_CLIENT_ID=AD_CLIENT_ID, ";
					JSONObject jsonObj = dataArray.getJSONObject(i);
					for (String key : KEYS) {
						Object obj = jsonObj.get(key);
						if (jsonObj.keySet().contains(key) && null != obj) {
							sql += key + "=?,";
							params.add(obj);
						}
					}
					sql = sql.substring(0, sql.lastIndexOf(","));
					sql += " where Emeso_Manu_Process_Data_ID = ?";
					params.add(jsonObj.get("Emeso_MANU_PROCESS_DATA_ID"));
					service.executeSql(sql, params.toArray());
					params.clear();
				}
				msg.setOkMessage("保存成功！");
			} else {
				msg.setErrorMessage("保存失败！");
			}
		} else {
			msg.setErrorMessage("保存失败！");
		}
		return msg;
	}

	@ResponseBody
	@PostMapping("getEmesProcessList")
	public Message getEmesProcessList(HttpServletRequest request) {
		Message msg = new Message();
		String orgId = (String) request.getSession().getAttribute("orgId");
		List<Map<String, Object>> emesProcessList = this.dcService.getEmesProcessList(orgId);
		msg.setData("emesProcessList", emesProcessList);
		return msg;
	}

	/**
	 * 返工操作
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("rework")
	@Transactional
	public Message rework(HttpServletRequest request) {
		Message msg = new Message();
		User user = (User) request.getSession().getAttribute(UserUtil.USERSESSION);
		String orgId = (String) request.getSession().getAttribute("orgId");
		String code = request.getParameter("code");
		String facCode = request.getParameter("facCode");
		String orderCode = request.getParameter("orderCode");
		String reworkReason = request.getParameter("reworkReason");
		String description = request.getParameter("description");

		//根据页面编码获取工序信息
		DataCollectionPage pageInfo = dcService.getDataCollectionPage(code);
		if (pageInfo == null) {
			msg.setErrorMessage("编码[" + code + "]未找到对应的生产采集页面信息！");
			return msg;
		} else if (pageInfo.getProcessId() == null) {
			msg.setErrorMessage("当前车间不能执行工序：" + pageInfo.getName() + "！");
			return msg;
		}
		//验证上道工序是否已完工
		String error = dcService.checkBatchProcess(orderCode, pageInfo.getProcessId());
		if (error != null && !"".equals(error)) {
			msg.setErrorMessage(error);
			return msg;
		}
		//获取工序配置信息
		Map<String, Object> process = processService.getProcessInfo(pageInfo.getProcessId());

		//执行当前工序
		dcService.saveJobOrder(orderCode, (String) process.get("ID"), (String) process.get("NAME"), orgId, user.getId(), facCode, "START", reworkReason, description);
		//并跳转至调温工序
		final int routeNoRepeat = 80;
		Map<String, Object> processRepeat = processService.getOrgProcess(orgId, routeNoRepeat);
		//修改工单工序状态为调温工序
		String sql = "update Emeso_Manu_Batch set emes_process_Id = ? "
				+ " where Emeso_Manu_Batch_id = ?";
		service.executeSql(sql, (String) processRepeat.get("ID"), orderCode);
		msg.setOkMessage("保存成功！");
		return msg;
	}

	/**
	 * 处理扫码后根据工序亮灯不同的仓库
	 */
	private void outMaterialToWms(String processOprId, String orderCode) {
		//拉邦工序调用立库下架
		if ("62279959A0E44B738046113DEECE95B3".equalsIgnoreCase(processOprId)) {
			//验证立库是否已下架
			String sql = "select out_lk from emeso_job_order where code = ?";
			Map<String, Object> result = service.queryUnique(sql, orderCode);

			//验证立库是否已下架
			if (result != null && !"Y".equalsIgnoreCase((String)result.get("out_lk"))) {
				int qty = WCSUtils.check("LK", orderCode);
				if (qty > 0) {
					//调用立库下架
					WCSUtils.outStorck("LK", orderCode, 1, orderCode);

					//修改立库状态为已下架
					sql = "update emeso_job_order set out_lk = 'Y' where code = ?";
					service.executeSql(sql, orderCode);
				}
			}
		} else if ("9DD361E2A06E49FE93ECDD751E79CB57".equalsIgnoreCase(processOprId)) {
			//压底模下架
			String sql = "select code, bi.foot_type from wms_storage_batch_item bi, wms_storage_batch sb \n" +
					"where bi.wms_storage_batch_id = sb.wms_storage_batch_id\n" +
					"  and exists (\n" +
					"\t\tselect p.yadimo_id, po.emes_size_id\n" +
					"\t\t from emesp_planorder po, emeso_manuorder mo, emes_pbom p, emeso_job_order jo\n" +
					"\t\t where po.emesp_planorder_id = mo.emesp_planorder_id\n" +
					"\t\t   and sb.m_product_id = p.yadimo_id\n" +
					"\t\t\t and sb.emes_size_id = po.emes_size_id\n" +
					"\t\t\t and mo.emeso_manuorder_id = jo.emeso_manuorder_id\n" +
					"\t\t\t and p.m_product_id = jo.m_product_id\n" +
					"		and nvl(jo.out_ydm, '') <> 'Y'" +//状态为未取料
					"\t\t\t and jo.code = ?\n" +
					")";
			List<Map<String, Object>> list = service.query(sql, orderCode);
			String leftCode = null;
			String rightCode = null;
			for (Map<String, Object> map : list) {
				if ("left".equalsIgnoreCase(map.get("foot_type").toString()) && leftCode == null) {
					leftCode = (String)map.get("code");
					int qty = WCSUtils.check("YD", leftCode);
					if (qty > 0) {
						//调用压底模库下架
						WCSUtils.outStorck("YD", leftCode, 1, orderCode);
					} else {
						leftCode = null;
					}
				} else if ("right".equalsIgnoreCase(map.get("foot_type").toString()) && rightCode == null) {
					rightCode = (String)map.get("code");
					int qty = WCSUtils.check("YD", rightCode);
					if (qty > 0) {
						//调用压底模库下架
						WCSUtils.outStorck("YD", rightCode, 1, orderCode);
					} else {
						rightCode = null;
					}
				}
				if (leftCode != null && rightCode != null) {
					break;
				}
			}
			//压低模取料成功修改已取料状态
			if (leftCode != null && rightCode != null) {
				sql = "update emeso_job_order set out_ydm = 'Y' where code = ?";
				service.executeSql(sql, orderCode);
			}
		}
	}
}